import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:intl/intl.dart';
import 'package:family_app/src/theme/app_theme.dart';

/// u6708u4efdu9009u62e9u5668
class MonthSelector extends StatelessWidget {
  final DateTime selectedMonth;
  final Function(DateTime) onMonthChanged;

  const MonthSelector({
    Key? key,
    required this.selectedMonth,
    required this.onMonthChanged,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 12.h),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        boxShadow: AppTheme.lightShadow,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          IconButton(
            icon: const Icon(Icons.chevron_left),
            onPressed: () => _selectPreviousMonth(),
            color: AppTheme.primaryColor,
          ),
          GestureDetector(
            onTap: () => _showMonthPicker(context),
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 8.w),
              child: Row(
                children: [
                  Text(
                    DateFormat.yMMM('zh_CN').format(selectedMonth),
                    style: TextStyle(
                      fontSize: 16.sp, 
                      fontWeight: FontWeight.bold,
                      color: AppTheme.textPrimaryColor,
                    ),
                  ),
                  SizedBox(width: 4.w),
                  const Icon(Icons.arrow_drop_down,
                      color: AppTheme.primaryColor),
                ],
              ),
            ),
          ),
          IconButton(
            icon: const Icon(Icons.chevron_right),
            onPressed: _canSelectNextMonth() ? () => _selectNextMonth() : null,
            color: _canSelectNextMonth()
                ? AppTheme.primaryColor
                : Colors.grey[400],
          ),
        ],
      ),
    );
  }

  /// u9009u62e9u4e0au4e00u4e2au6708
  void _selectPreviousMonth() {
    final previousMonth =
        DateTime(selectedMonth.year, selectedMonth.month - 1, 1);
    onMonthChanged(previousMonth);
  }

  /// u9009u62e9u4e0bu4e00u4e2au6708
  void _selectNextMonth() {
    if (_canSelectNextMonth()) {
      final nextMonth =
          DateTime(selectedMonth.year, selectedMonth.month + 1, 1);
      onMonthChanged(nextMonth);
    }
  }

  /// u662fu5426u53efu4ee5u9009u62e9u4e0bu4e00u4e2au6708uff08u4e0du80fdu8d85u8fc7u5f53u524du6708u4efduff09
  bool _canSelectNextMonth() {
    final now = DateTime.now();
    final currentMonth = DateTime(now.year, now.month, 1);
    final nextMonth = DateTime(selectedMonth.year, selectedMonth.month + 1, 1);
    return nextMonth.compareTo(currentMonth) <= 0;
  }

  /// u663eu793au6708u4efdu9009u62e9u5668
  void _showMonthPicker(BuildContext context) async {
    final now = DateTime.now();
    final firstDate = DateTime(now.year - 5, 1, 1); // 5u5e74u524d
    final lastDate = DateTime(now.year, now.month, 1); // u5f53u524du6708

    showDialog(
      context: context,
      builder: (context) => Dialog(
        shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(16.r)),
        child: Padding(
          padding: EdgeInsets.all(16.r),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '\u9009\u62E9\u6708\u4efd',
                style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 16.h),
              SizedBox(
                height: 300.h,
                width: double.maxFinite,
                child: YearMonthGrid(
                  firstDate: firstDate,
                  lastDate: lastDate,
                  selectedDate: selectedMonth,
                  onMonthSelected: (date) {
                    Navigator.of(context).pop();
                    onMonthChanged(date);
                  },
                ),
              ),
              SizedBox(height: 16.h),
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('\u53D6\u6D88'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

/// u5e74u6708u7f51u683cu9009u62e9u5668
class YearMonthGrid extends StatefulWidget {
  final DateTime firstDate;
  final DateTime lastDate;
  final DateTime selectedDate;
  final Function(DateTime) onMonthSelected;

  const YearMonthGrid({
    Key? key,
    required this.firstDate,
    required this.lastDate,
    required this.selectedDate,
    required this.onMonthSelected,
  }) : super(key: key);

  @override
  State<YearMonthGrid> createState() => _YearMonthGridState();
}

class _YearMonthGridState extends State<YearMonthGrid> {
  late int _selectedYear;
  final List<int> _years = [];
  final List<String> _months = [
    '\u4e00\u6708',
    '\u4e8c\u6708',
    '\u4e09\u6708',
    '\u56db\u6708',
    '\u4e94\u6708',
    '\u516d\u6708',
    '\u4e03\u6708',
    '\u516b\u6708',
    '\u4e5d\u6708',
    '\u5341\u6708',
    '\u5344\u6708',
    '\u5345\u6708',
  ];

  @override
  void initState() {
    super.initState();
    _selectedYear = widget.selectedDate.year;
    _initYears();
  }

  void _initYears() {
    for (int year = widget.firstDate.year;
        year <= widget.lastDate.year;
        year++) {
      _years.add(year);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // u5e74u4efdu9009u62e9u5668
        SizedBox(
          height: 50.h,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: _years.length,
            itemBuilder: (context, index) {
              final year = _years[index];
              final isSelected = year == _selectedYear;
              return GestureDetector(
                onTap: () {
                  setState(() {
                    _selectedYear = year;
                  });
                },
                child: Container(
                  alignment: Alignment.center,
                  margin: EdgeInsets.symmetric(horizontal: 8.w),
                  padding:
                      EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
                  decoration: BoxDecoration(
                    color:
                        isSelected ? AppTheme.primaryColor : Colors.transparent,
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: Text(
                    '$year\u5e74',
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight:
                          isSelected ? FontWeight.bold : FontWeight.normal,
                      color:
                          isSelected ? Colors.white : AppTheme.textPrimaryColor,
                    ),
                  ),
                ),
              );
            },
          ),
        ),
        SizedBox(height: 16.h),
        // u6708u4efdu7f51u683c
        Expanded(
          child: GridView.builder(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
              childAspectRatio: 1.5,
            ),
            itemCount: 12,
            itemBuilder: (context, index) {
              final month = index + 1;
              final date = DateTime(_selectedYear, month, 1);
              final isSelected = widget.selectedDate.year == _selectedYear &&
                  widget.selectedDate.month == month;
              final isDisabled = date.isBefore(widget.firstDate) ||
                  date.isAfter(widget.lastDate);

              return GestureDetector(
                onTap: isDisabled ? null : () => widget.onMonthSelected(date),
                child: Container(
                  margin: EdgeInsets.all(4.r),
                  decoration: BoxDecoration(
                    color:
                        isSelected ? AppTheme.primaryColor : Colors.transparent,
                    borderRadius: BorderRadius.circular(8.r),
                    border: Border.all(
                      color: isDisabled
                          ? Colors.grey[300]!
                          : isSelected
                              ? AppTheme.primaryColor
                              : Colors.grey[400]!,
                    ),
                  ),
                  alignment: Alignment.center,
                  child: Text(
                    _months[index],
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: isDisabled
                          ? Colors.grey[400]
                          : isSelected
                              ? Colors.white
                              : AppTheme.textPrimaryColor,
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      ],
    );
  }
}
